﻿using BCT.Models;
using BCT.Repositories.DataAccess;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace BCT.Repositories
{
    public class UserRepository : IUserRepository
    {
        public LoginResultModel Login(LoginModel model)
        {
            using (var context = new EvaluateEntities())
            {

                string Salt = "!@#trtailw!#@";
                string Password = "";
                MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
                Password = BitConverter.ToString(MD5.ComputeHash(Encoding.GetEncoding("gb2312").GetBytes(model.Password + Salt))).Replace("-", "");


                var result = new LoginResultModel();
                var userinfo = context.User
                    .Where(s => s.Email == model.UserEmail && s.Password == Password)
                   .FirstOrDefault();
                if(userinfo != null && userinfo.Active == true)
                {
                    result.Status = true;
                    result.UserId = userinfo.UserId;
                    result.Role = userinfo.Role.RoleName;
                }
                else
                {
                    result.Status = false;
                }
                return result;
            }
        }
        public UserModel GetUserInfo(int id) {
            using(var context = new EvaluateEntities())
            {
                var userinfo = context.User
                    .Where(s => s.UserId == id)
                    .Select(s => new UserModel()
                    {
                        UserId = s.UserId,
                        Email = s.Email,
                        UserName = s.UserName,
                        Role = s.Role.RoleName

                    }).FirstOrDefault();
                return userinfo;
            }           
        }
    }
}
